package com.china08.yxyapi.api.manage.tec.teaching.lecture.prepare;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.china08.yxyapi.api.YxyApiBaseController;

/**
 * 教师课前准备-下载授课包-轮询下载状态接口
 * 
 */
@CrossOrigin
@Controller
public class LecturePrePackPollDownLoadController extends YxyApiBaseController {

    @Value("${yw.esbag.pack.tmp.dir}")
    private String userHome;

    @RequestMapping(value = "/api_yw/comm/lecture/prepare/poll/download", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void process(HttpServletRequest request, HttpServletResponse response, @RequestParam String packId,
            @RequestParam String userId, @RequestParam String packName) {

        // 备课包名称解码,防止乱码
        Base64 base64 = new Base64();
        byte[] decode = base64.decode(packName);
        // zip存放的路径
        String zipFilePath = getUserHome() + "/" + ".YxYun-YxYunApiTplForYw" + "/download/pack/" + userId + "/" + packId
                + "/" + "zip";
        // zip 存放的文件
        String zipName = new String(decode);
        File zipfile = new File(zipFilePath + "/" + zipName + ".zip");
        // 获得二进制输入流
        FileInputStream fileInputStream = null;
        // 缓存区，二进制输入流
        BufferedInputStream bufferedInputStream = null;
        // 二进制输出流
        OutputStream outputStream = null;
        // 缓存区二进制输出流
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 写明要下载的文件的大小
            response.setContentLength((int) zipfile.length());
            // 文件名
            String downloadFilename = zipfile.getName();
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
            // 指明response的返回对象是文件流
            response.setContentType("application/x-download");
            // 设置在下载框默认显示的文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);
            // 编码格式
            response.setCharacterEncoding("UTF-8");
            // 每次读取字节数 1024 * 10
            byte[] b = new byte[1024 * 10];
            // 获取本地zip文件输入流
            fileInputStream = new FileInputStream(zipfile);
            bufferedInputStream = new BufferedInputStream(fileInputStream, b.length);
            // 获取输出流
            outputStream = response.getOutputStream();
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            // 每次读取字节数
            int length;
            while ((length = bufferedInputStream.read(b, 0, b.length)) != -1) {
                bufferedOutputStream.write(b, 0, length);
            }
            outputStream.flush();

            // IOUtils.write(FileUtils.readFileToByteArray(zipfile),
            // response.getWriter());
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                }
            }
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                }
            }
            // 下载完成后删除服务器文件
            String filePath = getUserHome() + "/" + ".YxYun-YxYunApiTplForYw" + "/download/pack/" + userId + "/"
                    + packId;
            // 删除
            try {
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            System.gc();
                            Thread.sleep(3000);
                            deleteDir(new File(filePath));
                        } catch (Exception e) {
                        } finally {
                            try {
                                deleteDir(new File(filePath));
                            } catch (Exception e2) {
                            }
                        }
                    }
                });
                t.start();
            } catch (Exception e) {
            }

        }
        return;
    }

    public String getUserHome() {
        return userHome;
    }

    public void setUserHome(String userHome) {
        this.userHome = userHome;
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * 
     * @param dir
     *            将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful. If a
     *         deletion fails, the method stops attempting to delete and returns
     *         "false".
     */
    private void deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            // 递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                deleteDir(new File(dir + "/" + children[i]));
            }
            boolean result = dir.delete();
            if (!result) {
                System.gc();
                dir.delete();
            }
        } else {
            boolean result = dir.delete();
            if (!result) {
                System.gc();
                dir.delete();
            }
        }
    }

}
